package ua.at.tsvetkov.samizdat.fragments;

import android.app.Fragment;
import android.content.Intent;
import android.widget.AdapterView;
import android.widget.ListView;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import ua.at.tsvetkov.samizdat.Const;
import ua.at.tsvetkov.samizdat.R;
import ua.at.tsvetkov.samizdat.adapters.AdtGenres;

public class FrgGenres extends Fragment {

	private ListView	fragmentGenresListView;
	private AdtGenres	adapterFragmentGenres;

	private Integer	currentGenresClickedPosition = -1;;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.frg_genres, null);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		fragmentGenresListView = (ListView) getView().findViewById(R.id.fragment1ListView);
		fragmentGenresListView.setTextFilterEnabled(true);
		fragmentGenresListView.setOnItemClickListener(getFragment1ListViewOnItemClickListener());
		adapterFragmentGenres = new AdtGenres(this);
		adapterFragmentGenres.setSelectedRow(currentGenresClickedPosition);
		fragmentGenresListView.setAdapter(adapterFragmentGenres);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	public AdtGenres getFragmentGenresAdapter() {
		return adapterFragmentGenres;
	}

	private AdapterView.OnItemClickListener getFragment1ListViewOnItemClickListener() {
		return new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v, final int position, long id) {
				if (position != adapterFragmentGenres.getSelectedRow()) {
					adapterFragmentGenres.setSelectedView(v);
					adapterFragmentGenres.getSelectedView().setBackgroundResource(R.drawable.fragment2_item_bg_gradient);
					adapterFragmentGenres.setSelectedRow(position);
					currentGenresClickedPosition = position;
					v.setBackgroundResource(R.drawable.fragment2_item_bg_gradient_selected);
					adapterFragmentGenres.notifyDataSetChanged();
				}
				Intent clickIntent = getActivity().getIntent();
				clickIntent.putExtra(Const.FRAGMENT_GENRES_CLICK_POSITION, position);
				clickIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				getActivity().startActivity(clickIntent);
			}
		};
	}

}
